package com.kfm.web.dao;

import com.kfm.web.entity.User;
import com.kfm.web.util.DBHelper;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

public class LoginDao {
    private DBHelper db = new DBHelper();
    public User selectByUsernameAndPassword(String username, String password) {
        String hashedPassword = hashPassword(password); // 对用户输入的密码进行哈希加密

        String sql = "select user_name, password from sys_user where user_name = ? and password = ?";
        try {
            return db.selectOne(sql, User.class, username, hashedPassword);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = digest.digest(password.getBytes());

            StringBuilder builder = new StringBuilder();
            for (byte b : hashedBytes) {
                builder.append(String.format("%02x", b));
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to hash password", e);
        }
    }
}
